package com.emall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.common.constant.AuthConstant;
import com.common.utils.HttpUtils;
import com.common.utils.R;
import com.emall.auth.feign.MemberFeignService;
import com.emall.auth.vo.MemberRespVo;
import com.emall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author YuanShijia
 * @ClassName OAuth2Controller.java
 * @Description
 * @createTime 2020年05月25日 13:52:00
 */
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> header = new HashMap<>();
        Map<String, String> query = new HashMap<>();

        // 1. code -> accsess token
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id", "2202924514");
        map.put("client_secret", "ca5bf6cdf9d10eb08b01263ddfada46b");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://127.0.0.1:20000/oauth2/weibo/success/");
        map.put("code", code);

        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "POST", header, query, map);

        if (response.getStatusLine().getStatusCode() == 200){
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            // 如果用户第一次登录， 就自动注册进数据库
            // 登录或注册这个用户
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode() == 0){
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {});
                session.setAttribute(AuthConstant.LOGIN_USER,data);
                log.info("登录成功， 用户信息： {}"+ data.toString());
                return "redirect:http://127.0.0.1:10000/index.html";
            }else {
               return "redirect:http://127.0.0.1:20000/login.html";
            }
        }else {
            return "redirect:http://127.0.0.1:20000/login.html";
        }

        // 2. 登录成功返回首页

    }
}
